<?php
//定义分隔符
define('DS', DIRECTORY_SEPARATOR);
//定义root path
define('ROOT', dirname(__FILE__) . DS);
require('./class/AutoLoader.php');
spl_autoload_register('Autoloader::load');

//set path
Autoloader::$directory = ROOT;
Autoloader::$paths = array('./class/', './rsa/', './model/', './service/', './lib/', './config/', '../sdk/');
header("Content-Type: application/json; charset=utf-8");

$method = strtolower($_SERVER['REQUEST_METHOD']);
if ($method != 'post') {
    printError(201,'请使用POST方式请求');
}

//接口转向
$tmp = @explode('?', $_SERVER['REQUEST_URI']);
$tmp = @explode('/', $tmp[0]);
$api_method = $tmp[1];
$resource = checkMethod($api_method);

//日志
$postStr= file_get_contents("php://input");
//\Util\LogUtil::log('openapi_log',$postStr);

//引入config文件
define("ROOT_PATH", __DIR__ . "/");
define("APP_NAME", "openapi");
define('CONFIG_PATH', json_encode(array(ROOT_PATH . '../sdk/Config/',)));

//version
$version = 1;

if (empty($resource)) {
    printError(201,'暂时没有开放该接口');
} else {
    $file = './service/V' . $version . '/' . $resource . '.php';
    if (!file_exists($file)) {
        printError(201,'没有找到你要的接口资源');
    } else {
        $class = '\\V' . $version . '\\' . $resource;
        $obj = new $class();
        $result = array();
        $result = $obj->$method($postStr);
        echo json_encode($result);
        die();
    }
}

/*
 * 检查method
 */
function checkMethod($api_method)
{
    $resource = '';
    if ($api_method) {
        switch ($api_method) {
            case 'sf':
                $resource = 'SF';
                break;
            case 'ems':
                $resource = 'EMS';
                break;
            case 'sfroute':
                $resource = 'SFroute';
                break;
            default:
                break;
        }
    }
    return $resource;
}

//添加日志
function addLog($resource, $data)
{
    $log_dir = sys_get_temp_dir() . '/xyt/';
    if (!file_exists($log_dir)) {
        mkdir($log_dir);
    }
    $log_file = sys_get_temp_dir() . '/xty/' . $resource . '-' . date('Ymd') . '.txt';
    $log_data = array('request_time' => date('Y-m-d H:i:s'), 'request_uri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '', 'data' => json_encode($data));
    file_put_contents($log_file,json_encode($log_data),FILE_APPEND);
}

//错误输出
function printError($error_code = 201,$ErrorMsg = '',$result = array())
{
    $data['code'] = $error_code;
    $data['message'] = $ErrorMsg;
    $data['result'] = $result;
    echo json_encode($data);
    exit;
}